# -*- coding: utf-8 -*-
"""
@File    : qinghai_hibzz_policy
@Author  : caojy
"""
import scrapy
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class QinghaiHibzzPolicy(BaseTaxPolicySpider):
    name = 'qinghai_hibzz_policy'

    province = '青海省'
    city = '海北藏族自治州'
    county = ''
    park = ''

    def start_requests(self):
        for source, county, url in [
            ['海北藏族自治州人民政府', '', 'https://www.haibei.gov.cn/public/column/6616331?type=4&catId=6719111&action=list&nav=3'],
            ['海北藏族自治州发展和改革委员会', '', 'http://fgw.haibei.gov.cn/public/column/6616341?type=4&catId=6721451&action=list&nav=3'],
            ['海北藏族自治州工业商务和信息化局', '', 'http://gxj.haibei.gov.cn/public/column/6616361?type=4&catId=6721451&action=list&nav=3'],
            ['海北藏族自治州财政局', '', 'http://zczj.haibei.gov.cn/public/column/6616411?type=4&catId=6721101&action=list&nav=3'],
            ['海北藏族自治州人力资源社会保障局', '', 'http://rsj.haibei.gov.cn/public/column/6616421?type=4&catId=6721101&action=list&nav=3'],
            ['海北藏族自治州交通运输局', '', 'http://jtysj.haibei.gov.cn/public/column/6616461?type=4&catId=6721451&action=list&nav=3'],
            ['海北藏族自治州农牧和科技局', '', 'http://nmj.haibei.gov.cn/public/column/6616481?type=4&catId=6721451&action=list&nav=3'],
            ['海北藏族自治州文体旅游广电局', '', 'http://wtlygd.haibei.gov.cn/public/column/6616491?type=4&catId=6721101&action=list&nav=3'],
            ['海北藏族自治州文体旅游广电局', '', 'http://wtlygd.haibei.gov.cn/public/column/6616491?type=4&catId=6721451&action=list&nav=3'],
            ['海晏县人民政府', '海晏县', 'https://www.haiyanxian.gov.cn/public/column/6617021?type=4&catId=6723311&action=list&nav=3'],
            ['海晏县人民政府', '海晏县', 'https://www.haiyanxian.gov.cn/public/column/6617021?type=4&catId=6723321&action=list&nav=3'],
            ['祁连县人民政府', '祁连县', 'http://www.qilian.gov.cn/public/column/6617001?type=4&catId=6722531&action=list&nav=3'],
            ['门源县人民政府', '门源县', 'https://www.menyuan.gov.cn/public/column/6617041?type=4&catId=6724741&action=list&nav=3'],
            ['门源县人民政府', '门源县', 'https://www.menyuan.gov.cn/public/column/6617041?type=4&catId=6724751&action=list&nav=3'],
            ['门源县人民政府', '门源县', 'https://www.menyuan.gov.cn/public/column/6617041?type=4&catId=6723621&action=list&nav=3'],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={"item": item})

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        elem_list = response.xpath(
            "//ul[@class='pageTPList' or @class='infoList']/li//a[@title]/ancestor::li[string-length(string(.))>=10] |"
            "//li[@class='clearfix']//a[@title]/ancestor::li[string-length(string(.))>=10]"
        )
        if not elem_list:
            yield response.follow(response.url, callback=self.parse_list, meta=response.meta, dont_filter=True)
            return
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.pdf' in item['source_url'] or '.doc' in item['source_url']:
                continue
            else:
                print(response.url, item['source_url'])
                yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total_page = response.xpath(""".""").re_first(r"""pageCount\s*:\s*\((\d+)\s*""")
            if not total_page:
                print(total_page, response.text)
            print(response.url, "page:", total_page)
            for page_num in range(2, int(total_page) + 1):
                yield response.follow(response.url + f'&pageIndex={page_num}',
                                      callback=self.parse_list, meta={'item': prev_item, 'is_next': False}, dont_filter=True)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl qinghai_hibzz_policy".split())
